package com.gtlab1207.br_awareness.common;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import com.gtlab1207.br_awareness.models.domain.LogHost;
import com.gtlab1207.br_awareness.models.domain.LogRecord;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import static com.gtlab1207.br_awareness.common.Constant.SECURITY_LOG;
import static com.gtlab1207.br_awareness.common.Constant.SURICATA_LOG;

/**
 * 拿日志工具类
 */
@Component
public class LogUtil {
//    @Value("${linux.ip}")
//    private String ip;
//    @Value("${linux.username}")
//    private String username;
//    @Value("${linux.password}")
//    private String password;
//    @Value("${linux.port}")
//    private Integer port;

    private Connection conn = null;
    private Session ssh = null;
    private BufferedReader br = null;

    // 建立连接
    public Boolean connect(LogHost logHost, String cmd) {
        //指明连接主机的IP地址
        conn = new Connection(logHost.getIpAddress());
        try {
            //连接到主机
            conn.connect();
            //使用用户名和密码校验
            boolean isconn = conn.authenticateWithPassword(logHost.getUser(), logHost.getPassword());
            if (!isconn) {
                System.out.println("用户名称或者是密码不正确");
            }
            // System.out.println("已经连接到" + ip);
            // 开启一个会话
            ssh = conn.openSession();
            ssh.execCommand(cmd);
            InputStream is = new StreamGobbler(ssh.getStdout());
            br = new BufferedReader(new InputStreamReader(is));
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }// 这里先不关闭，用完再关闭
    }

    /**
     * 筛选Suricata日志数据封装成写入对象
     * @param line
     * @param date
     * @return
     */
    public LogRecord packSuricata(String line, Date date) {
        // 筛选数据
        String[] split = line.split(" ");
        // 获取sip和dip
        String sip = split[split.length-3].substring(0,split[split.length-3].indexOf(":"));
        String dip = split[split.length-1].substring(0,split[split.length-1].indexOf(":"));
        String event = "";
        int i = 4;
        for (; i< split.length; i++) {
            if (split[i].equals("[**]")) {
                break;
            }
            event += split[i] + " ";
        }
        i++;
        for (; i<split.length; i++) {
            if (split[i].equals("[Priority:")) {
                break;
            }
            event += split[i] + " ";
        }
        event = event.substring(0,event.lastIndexOf(" "));

        // 封装
        LogRecord logRecord = new LogRecord();
        logRecord.setTime(date);
        logRecord.setSip(sip);
        logRecord.setDip(dip);
        logRecord.setEvent(event);
        logRecord.setType(SURICATA_LOG);
        return logRecord;
    }

    /**
     * Suricata日志 日期的转化
     * @param line
     * @return
     */
    public Date getSuricataDate(String line) throws Exception {
        // 筛选数据
        String[] split = line.split(" ");
        // 获取日期
        SimpleDateFormat sdf =  new SimpleDateFormat("MM/dd/yyyy-HH:mm:ss");
        String preTime = split[0].substring(0, split[0].indexOf("."));
        Date date = null;
        date = sdf.parse(preTime);
        return date;
    }

    /**
     * 筛选Security模块日志数据封装成写入对象
     * @param line
     * @param date
     * @return
     */
    public LogRecord packSecurity(String line, Date date, String ipAddress) throws UnknownHostException {
        // 筛选数据
        String[] split = line.split("-");
        String event = split[split.length-1].substring(1);
        // 封装
        LogRecord logRecord = new LogRecord();
        logRecord.setTime(date);
        logRecord.setDip(ipAddress);
        logRecord.setEvent(event);
        logRecord.setType(SECURITY_LOG);
        return logRecord;
    }

    /**
     * Security日志 日期的转化
     * @param line
     * @return
     */
    public Date getSecurityDate(String line) throws Exception {
        // 筛选数据
        String[] split = line.split(",");
        // 获取日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String preTime = split[0];
        Date date = null;
        date = sdf.parse(preTime);
        return date;
    }

    public Connection getConn() {
        return conn;
    }

    public Session getSsh() {
        return ssh;
    }

    public BufferedReader getBr() {
        return br;
    }
}
